//
//  PhoneCodeLoginView.m
//  HomeDelivery
//
//  Created by apple on 16/7/21.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PhoneCodeLoginView.h"
@implementation PhoneCodeLoginView

-(id)initWithFrame:(CGRect)frame
{
    if (self=[super initWithFrame:frame]) {
        [self setUpTxView];
        _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeText) userInfo:nil repeats:YES];
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return self;
}
-(void)changeText
{
    if (_second==0)
    {
       [_timer setFireDate:[NSDate distantFuture]];
        [codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
    }else
    {
      [codeBtn setTitle:[NSString stringWithFormat:@"%zd秒",_second] forState:UIControlStateNormal];
    }
    _second--;
}
#pragma mark--创建输入框所在的view
-(void)setUpTxView
{
    _whiteView=[[UIView alloc]initWithFrame:CGRectMake(0, 20, self.frame.size.width, 101)];
    _whiteView.backgroundColor=[UIColor whiteColor];
    [self addSubview:_whiteView];
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 50,WIDTH, 1)];
    lineView.backgroundColor=LIGHTGRAY;
    [_whiteView addSubview:lineView];
    
    for (int i=0; i<2; i++)
    {
        UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(10, i*(30+21)+10, 30, 30)];
        image.image=[UIImage imageNamed:@[@"login_moible",@"login_auth"][i]];
        [_whiteView addSubview:image];
        
        UITextField *tx=[[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(image.frame), i*(50+1), WIDTH-50, 50)];
        tx.textColor=[UIColor darkGrayColor];
        tx.font=[UIFont systemFontOfSize:15];
        tx.tag=(i+1)*100;
        tx.keyboardType=UIKeyboardTypePhonePad;
        tx.clearButtonMode=UITextFieldViewModeWhileEditing;
        tx.placeholder=@[@"请输入手机号码",@"请输入手机验证码"][i];
        [_whiteView addSubview:tx];
    }
    UITextField *textFieldOne=[_whiteView viewWithTag:100];
    CGRect rect = textFieldOne.frame;
    rect.size.width = WIDTH-50-90;
    textFieldOne.frame = rect;
    //获取验证码按钮
   codeBtn=[[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(textFieldOne.frame),10, 80, 30)];
    [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    codeBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    codeBtn.backgroundColor=ORANGE;
    codeBtn.layer.cornerRadius=5;
    codeBtn.clipsToBounds=YES;
    [codeBtn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    [_whiteView addSubview:codeBtn];
    //登录按钮
    UIButton *loginBtn=[[UIButton alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(_whiteView.frame)+50, WIDTH-20, 50)];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.backgroundColor=ORANGE;
    loginBtn.layer.cornerRadius=5;
    loginBtn.clipsToBounds=YES;
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(goLogin) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:loginBtn];
    
}

#pragma mark--获取验证码
-(void)getCode:(UIButton *)btn
{
    UITextField *mobile=[_whiteView viewWithTag:100];

    if ([[btn titleForState:UIControlStateNormal]hasSuffix:@"秒"]) {
        return;
    }
    if (mobile.text.length==0) {
        [MBProgressHUD showError:@"请输入手机号"];
        [mobile becomeFirstResponder];
    }else if ([GeneralTool valiMobile:mobile.text])
    {
        [MBProgressHUD showError:[GeneralTool valiMobile:mobile.text]];
        [mobile becomeFirstResponder];

    }else
    {
        UITextField *mobile=[_whiteView viewWithTag:100];

        //http://192.168.1.107:3722/User/VerifyCode
        //m_VerifyCodePara(Mobile,ClientType,Timestamp,Sign)
        NSString *timeStamp=[GeneralTool gettimestamp];
        [MBProgressHUD showHUDAddedTo:self animated:YES];
        NSDictionary *dic=@{@"Mobile":mobile.text,
                            @"ClientType":CLIENTTYPE,
                            @"Timestamp":timeStamp};
        NSString *sign=[GeneralTool GetSin:dic];
        NSDictionary *dataDic=@{@"Mobile":mobile.text,
                                @"ClientType":CLIENTTYPE,
                                @"Timestamp":timeStamp,
                                @"Sign":sign};
        NSDictionary *requestDic=@{@"m_VerifyCodePara":dataDic};
        [RequestTool requestDataWithType:@"post" andUrlString:@"User/VerifyCode" andParameters:requestDic andFinishedWith:^(id response, NSError *error) {
            [MBProgressHUD hideHUDForView:self];
            if (error)
            {
                [MBProgressHUD showError:@"请求失败"];
            }else
            {
                if ([response[@"IsSuccess"]integerValue]==1)
                {
                    _second=60;
                    [_timer setFireDate:[NSDate distantPast]];
                     [MBProgressHUD showSuccess:response[@"ReturnString"]];
                }else
                {
                    [MBProgressHUD showError:response[@"ReturnString"]];
                    
                }
            }

            
        }];
    }
 
}
#pragma mark--登录
-(void)goLogin
{
    UITextField *mobile=[_whiteView viewWithTag:100];
    UITextField *code=[_whiteView viewWithTag:200];
    if (mobile.text.length==0) {
        [MBProgressHUD showError:@"请输入手机号"];
    }else if ([GeneralTool valiMobile:mobile.text]!=nil)
    {
        [MBProgressHUD showError:[GeneralTool valiMobile:mobile.text]];
    }
    else if (code.text.length==0)
    {
        [MBProgressHUD showError:@"请输入验证码"];
        
    }else
    {
        //http://192.168.1.107:3722/User/MobileLogin
        //m_MobileLoginPara(Mobile,Code,Timestamp,Sign)
        NSString *timeStamp=[GeneralTool gettimestamp];
        
        NSDictionary *dic=@{@"Mobile":mobile.text,
                            @"Code":code.text,
                            @"ClientType":CLIENTTYPE,
                            @"Timestamp":timeStamp};
        NSString *sign=[GeneralTool GetSin:dic];
        NSDictionary *dataDic=@{@"Mobile":mobile.text,
                                @"Code":code.text,
                                @"ClientType":CLIENTTYPE,
                                @"Timestamp":timeStamp,
                                @"Sign":sign};
        NSDictionary *requestDic=@{@"m_MobileLoginPara":dataDic};
        [RequestTool requestDataWithType:@"post" andUrlString:@"User/MobileLogin" andParameters:requestDic andFinishedWith:^(id response, NSError *error) {
            if (error)
            {
                [MBProgressHUD showError:@"请求失败"];
            }else
            {
                if ([response[@"IsSuccess"]integerValue]==1)
                {
                    //登陆成功
                    NSDictionary *dic=response[@"ReturnObject"];
                    NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
                    [data setObject:dic[@"AdminAccount"] forKey:@"AdminAccount"];
                    [data setObject:dic[@"MerchantAccId"] forKey:@"MerchantAccId"];
                    [data synchronize];
                    
                    TabBarViewController *tabBar=[[TabBarViewController alloc]init];
                    UIWindow *window=[UIApplication sharedApplication].keyWindow;
                    window.rootViewController=tabBar;
                    /*
                     ReturnObject =     {
                     AdminAccount = 10001001;
                     CityCode = 310100;
                     IsFirstLogin = 0;
                     MerchantAccId = 100010;
                     Mobile = 13127513977;
                     };
                     
                     */
                }else
                {
                    [MBProgressHUD showError:response[@"ReturnString"]];
                    
                }
            }
            

            
        }];
    }

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}
@end
